<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Common\Constant\Status;
use App\Events\CouponAssign;
use App\Events\MasterOrderRefund;
use App\Events\MerchantOrderRefund;
use App\Events\OrderRefunded;
use App\Models\Coupon;
use App\Models\Merchant;
use App\Models\OrderRefund;
use App\Notifications\OrderNotifications\MerchantOrderRefundNotification;
use App\Notifications\OrderNotifications\OrderRefundNotification;
use App\Services\ICouponService;
use App\Services\ISystemService;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class CouponAssignListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'finance';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CacheHit  $event
     * @return void
     */
    public function handle(CouponAssign $event)
    {
        $merchant = Merchant::find($event->merchant_id);
        if(!$merchant){
            throw new \Exception('miss merchant');
        }

        $coupon = Coupon::find($event->coupon_id);
        if(!$coupon){
            throw new \Exception('miss coupon');
        }

        $ret = resolve(ICouponService::class)->assign($event->merchant_id,$event->coupon_id,$event->count);
        if($ret == Status::COUPON_NOT_ENOUGH){
            throw new \Exception(status($ret));
        }
        if(!$ret){
            throw new \Exception('coupon assign fail');
        }
    }

    public function failed(CouponAssign $event, \Exception $exception)
    {
        //
    }
}
